package com.campus.activity.controller;

import com.campus.activity.common.Result;
import com.campus.activity.entity.Activity;
import com.campus.activity.entity.User;
import com.campus.activity.entity.Registration;
import com.campus.activity.entity.Feedback;
import com.campus.activity.service.ActivityService;
import com.campus.activity.service.UserService;
import com.campus.activity.service.RegistrationService;
import com.campus.activity.service.FeedbackService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 * 
 * @author System
 * @since 2024
 */
@RestController
@RequestMapping("/admin")
@Tag(name = "管理员管理", description = "管理员相关接口")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private ActivityService activityService;
    
    @Autowired
    private RegistrationService registrationService;
    
    @Autowired
    private FeedbackService feedbackService;

    @GetMapping("/dashboard/stats")
    @Operation(summary = "获取仪表板统计数据", description = "获取管理员仪表板的统计信息")
    public Result<Map<String, Object>> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 获取用户统计
        List<User> allUsers = userService.list();
        long totalUsers = allUsers.size();
        long studentCount = allUsers.stream().filter(u -> "STUDENT".equals(u.getUserRole())).count();
        long organizerCount = allUsers.stream().filter(u -> "ORGANIZER".equals(u.getUserRole())).count();
        
        // 获取活动统计
        List<Activity> allActivities = activityService.list();
        long totalActivities = allActivities.size();
        long publishedActivities = allActivities.stream().filter(a -> "PUBLISHED".equals(a.getActivityType())).count();
        
        stats.put("totalUsers", totalUsers);
        stats.put("studentCount", studentCount);
        stats.put("organizerCount", organizerCount);
        stats.put("totalActivities", totalActivities);
        stats.put("publishedActivities", publishedActivities);
        
        return Result.success(stats);
    }

    @GetMapping("/users")
    @Operation(summary = "获取所有用户", description = "获取系统中所有用户列表")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.list();
        return Result.success(users);
    }

    @GetMapping("/students")
    @Operation(summary = "获取所有学生", description = "获取系统中所有学生用户")
    public Result<List<User>> getAllStudents() {
        List<User> students = userService.getUsersByRole("STUDENT");
        return Result.success(students);
    }

    @GetMapping("/organizers")
    @Operation(summary = "获取所有组织者", description = "获取系统中所有组织者用户")
    public Result<List<User>> getAllOrganizers() {
        List<User> organizers = userService.getUsersByRole("ORGANIZER");
        return Result.success(organizers);
    }

    @GetMapping("/activities")
    @Operation(summary = "获取所有活动", description = "获取系统中所有活动")
    public Result<List<Activity>> getAllActivities() {
        List<Activity> activities = activityService.list();
        return Result.success(activities);
    }

    @DeleteMapping("/users/{userId}")
    @Operation(summary = "删除用户", description = "删除指定用户")
    public Result<Boolean> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Integer userId) {
        boolean success = userService.removeById(userId);
        return success ? Result.success("用户删除成功", true) : Result.error("用户删除失败");
    }

    @DeleteMapping("/activities/{activityId}")
    @Operation(summary = "删除活动", description = "删除指定活动")
    public Result<Boolean> deleteActivity(
            @Parameter(description = "活动ID") @PathVariable Integer activityId) {
        boolean success = activityService.deleteActivity(activityId);
        return success ? Result.success("活动删除成功", true) : Result.error("活动删除失败");
    }

    @GetMapping("/statistics/users")
    @Operation(summary = "获取用户统计", description = "获取用户相关的统计数据")
    public Result<Map<String, Object>> getUserStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        List<User> allUsers = userService.list();
        long totalUsers = allUsers.size();
        long studentCount = allUsers.stream().filter(u -> "STUDENT".equals(u.getUserRole())).count();
        long organizerCount = allUsers.stream().filter(u -> "ORGANIZER".equals(u.getUserRole())).count();
        long adminCount = allUsers.stream().filter(u -> "ADMIN".equals(u.getUserRole())).count();
        
        stats.put("totalUsers", totalUsers);
        stats.put("studentCount", studentCount);
        stats.put("organizerCount", organizerCount);
        stats.put("adminCount", adminCount);
        
        return Result.success(stats);
    }

    @GetMapping("/statistics/activities")
    @Operation(summary = "获取活动统计", description = "获取活动相关的统计数据")
    public Result<Map<String, Object>> getActivityStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        List<Activity> allActivities = activityService.list();
        long totalActivities = allActivities.size();
        long publishedActivities = allActivities.stream().filter(a -> "PUBLISHED".equals(a.getActivityType())).count();
        long draftActivities = allActivities.stream().filter(a -> "DRAFT".equals(a.getActivityType())).count();
        
        stats.put("totalActivities", totalActivities);
        stats.put("publishedActivities", publishedActivities);
        stats.put("draftActivities", draftActivities);
        
        return Result.success(stats);
    }

    // 注册管理接口
    @GetMapping("/registrations")
    @Operation(summary = "获取所有注册记录", description = "获取系统中所有注册记录")
    public Result<List<Registration>> getAllRegistrations() {
        List<Registration> registrations = registrationService.list();
        return Result.success(registrations);
    }

    @DeleteMapping("/registrations/{registrationId}")
    @Operation(summary = "删除注册记录", description = "删除指定注册记录")
    public Result<Boolean> deleteRegistration(
            @Parameter(description = "注册ID") @PathVariable Integer registrationId) {
        boolean success = registrationService.removeById(registrationId);
        return success ? Result.success("注册记录删除成功", true) : Result.error("注册记录删除失败");
    }

    // 反馈管理接口
    @GetMapping("/feedbacks")
    @Operation(summary = "获取所有反馈", description = "获取系统中所有反馈")
    public Result<List<Feedback>> getAllFeedbacks() {
        List<Feedback> feedbacks = feedbackService.list();
        return Result.success(feedbacks);
    }

    @DeleteMapping("/feedbacks/{feedbackId}")
    @Operation(summary = "删除反馈", description = "删除指定反馈")
    public Result<Boolean> deleteFeedback(
            @Parameter(description = "反馈ID") @PathVariable Integer feedbackId) {
        boolean success = feedbackService.removeById(feedbackId);
        return success ? Result.success("反馈删除成功", true) : Result.error("反馈删除失败");
    }

    // 系统管理接口
    @GetMapping("/system/info")
    @Operation(summary = "获取系统信息", description = "获取系统基本信息")
    public Result<Map<String, Object>> getSystemInfo() {
        Map<String, Object> systemInfo = new HashMap<>();
        systemInfo.put("systemName", "活动报名管理系统");
        systemInfo.put("version", "1.0.0");
        systemInfo.put("author", "System");
        systemInfo.put("description", "校园活动报名管理系统");
        return Result.success(systemInfo);
    }

    @GetMapping("/system/status")
    @Operation(summary = "获取系统状态", description = "获取系统运行状态")
    public Result<Map<String, Object>> getSystemStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("status", "running");
        status.put("uptime", System.currentTimeMillis());
        status.put("memory", Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
        return Result.success(status);
    }
}